#include <vector> //vector
#include <sstream> // ostringstream
#include <ostream> // ostream

#include "RPLeaf.h"

using namespace std;

RPLeaf::RPLeaf( const RPTreeParam &param, vector<unsigned int> &dataIdx, list< list<unsigned int> > &leavesContent, unsigned int depth, unsigned int &id )
: RPTree(), id(id++)
{
	list<unsigned int> tmp(dataIdx.begin(), dataIdx.end());
	leavesContent.push_back(tmp);
	this->depth = depth;

	this->v = vector<double>( param.ncol(), 0 );
	for( vector<unsigned int>::iterator i = dataIdx.begin() ; i!=dataIdx.end() ; i++ )
	{
		for( unsigned int j=0 ; j<param.ncol() ; j++ )
		{
			v[j] += param.get(*i,j);
		}
	}	

	for( unsigned int j=0 ; j<param.ncol() ; j++ )
	{
		v[j] /= dataIdx.size();
	}
}

RPLeaf::RPLeaf( unsigned int depth, unsigned int &id, vector<double> &v )
: RPTree(), id(id++)
{
	this->v = vector<double>(v);
	this->depth = depth;
}

RPLeaf::RPLeaf( unsigned int depth, unsigned int &id )
: RPTree(), id(id++)
{
	this->depth = depth;
}

RPLeaf::operator string() const
{
	ostringstream out;
	out<<this<<",LEAF,"<<id<<','<<depth<<",[,";

	for( vector<double>::const_iterator i = v.begin() ; i != v.end() ; i++ )
	{
		out<<*i<<',';
	}

	out<<"]";
	return out.str();
}

void RPLeaf::save( ostream &out ) const
{
	out<<(string) *this<<endl;
}

unsigned int RPLeaf::use(double *data) const
{
	return id;
}

const RPLeaf *RPLeaf::get_leaf_by_id(unsigned int id) const
{
	if(id == this->id)
	{
		return this;
	}

	return NULL;
}

unsigned int RPLeaf::get_id() const
{
	return id;
}
